#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowFlags( windowFlags() | Qt::WindowStaysOnTopHint );
    _bTop = true;
    _iCheckPos = 0;
    _iShowItem = 0;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushSetTop_clicked()
{
    if(_bTop)
    {
        ui->pushSetTop->setText( QString::fromUtf8("置顶") );
        setWindowFlags( windowFlags() & ~Qt::WindowStaysOnTopHint );
        show();
    }
    else
    {
        ui->pushSetTop->setText( QString::fromUtf8("取消置顶") );
        setWindowFlags( windowFlags() | Qt::WindowStaysOnTopHint );
        show();
    }
    _bTop = !_bTop;
}

void MainWindow::on_pushClear_clicked()
{
    QString text = ui->textEdit->toPlainText();
    if(text.length() > 0)
    {
        if(_iShowItem >= _history.length())
        {
            _history.append(text);
        }
        else if(text!=_history[_iShowItem])
        {
            _history[_iShowItem] = text;
        }
        ++_iShowItem;
        ui->textEdit->clear();
        _iCheckPos = 0;
    }
    ui->textEdit->setFocus();
}

void MainWindow::on_pushCheck_clicked()
{
    QTime now = QTime::currentTime();
    if(_lastCheckTime.secsTo(now) < 30)// too quickly, it must be a mistake
    {
        return;
    }
    _lastCheckTime = now;
    ++_iCheckPos;
    QString text = ui->textEdit->toPlainText();
    QString html;
    html.append("<font color='red'>");
    html.append( text.leftRef(_iCheckPos) );
    html.append("</font>");
    if(_iCheckPos < text.length())
    {
        html.append( text.rightRef(text.length()-_iCheckPos) );
    }
    ui->textEdit->setHtml(html);
}

void MainWindow::on_pushLast_clicked()
{
    if(_iShowItem < 1)
    {
        // wrong operation
        return;
    }
    QString text = ui->textEdit->toPlainText();
//    if(text.length() > 0)
    {
        if(_iShowItem >= _history.length())
        {
            _history.append(text);
        }
        else if(text!=_history[_iShowItem])
        {
            _history[_iShowItem] = text;
        }
    }
    --_iShowItem;
    ui->textEdit->setPlainText(_history[_iShowItem]);
}

void MainWindow::on_pushNext_clicked()
{
    if(++_iShowItem < _history.length())
    {
        ui->textEdit->setPlainText(_history[_iShowItem]);
    }
    else
    {
        --_iShowItem;
    }
}
